/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package br.gov.cemaden.agent.proxy;

import br.gov.cemaden.library.hibernate.HibernateUtil;
import java.lang.reflect.InvocationTargetException;
import org.hibernate.Session;

/**
 *
 * @author alan
 * @param <T>
 */
public class DaoFactory<T> {
    
    Session session;
    
    private T o;
    
    public DaoFactory(Class object){
        if(HibernateUtil.getSessionFactory().isClosed())
            session = HibernateUtil.getSessionFactory().openSession();
        else
            session = HibernateUtil.getSessionFactory().getCurrentSession();
        
        try {
            o = (T) object.getDeclaredConstructor(Session.class).newInstance(session);
        } catch (InstantiationException ex) {
            System.err.printf("InstantiationException ao tentar iniciar a classe %s%n%s", object.getName(), ex);
        } catch (IllegalAccessException ex) {
            System.err.printf("IllegalAccessException ao tentar iniciar a classe %s%n%s", object.getName(), ex);
        } catch (NoSuchMethodException ex) {
            System.err.printf("Erro ao invocar método construtor da classe %s%n%s", object.getName(), ex);
        } catch (SecurityException ex) {
            System.err.printf("Security ao tentar iniciar a classe %s%n%s", object.getName(), ex);
        } catch (IllegalArgumentException ex) {
            System.err.printf("Erro ao passar argumento para a classe %s%n%s", object.getName(), ex);
        } catch (InvocationTargetException ex) {
            System.err.printf("Erro ao tentar invocar construtor ou metodo para a classe %s%n%s", object.getName(), ex);
        }
    }
    
    public T get(){
        return o;
    }
    
}
